﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Catering.View_Operaction;
using System.Data;
using System.Text;
using System.Collections;
using System.Web.Services;
using Catering_Rules;
using Microsoft.Office.Core;
using System.IO;

namespace Catering.Catering_Page.richang
{
    public partial class SCP_ZiYing : System.Web.UI.Page
    {
        List<string> onworklist = new List<string>();//总岗位数
        public Catering_Model.TempGangWeiModel modelgangwei = new Catering_Model.TempGangWeiModel();

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {

            #region 初始化

            this.div_workinglist.InnerHtml = "";
            this.PersonForMSN.InnerHtml = "<li>总人数：0人</li>";

            #endregion

            #region 设置公司人数

            View_Monitor vm = new View_Monitor();
            DataTable dt = vm.GetZiYingCompanyAttendanceRecord();
            this.PersonForMSN.InnerHtml = string.Format("<li>总人数：{0}人</li>", dt.Rows.Count);

            #endregion

            #region 设置报表数据源

            InitData(dt);

            #region 字符串提取

            if (modelgangwei != null && modelgangwei.DanWeiList.Count > 0)
            {
                StringBuilder StrHtml = new StringBuilder("");

                #region 表头

                StrHtml.Append("<table border='0' cellpadding='0' cellspacing='1'>");
                StrHtml.Append("<tr>");
                StrHtml.Append("<th rowspan='2'>服务单位</th>");
                StrHtml.Append("<th rowspan='2'>总人数</th>");
                //StrHtml.Append("<th>&nbsp;</th>");
                StrHtml.Append("<th colspan='" + (onworklist.Count + 1) + "'>岗位</th>");
                StrHtml.Append("</tr>");
                StrHtml.Append("<tr>");
                for (int i = 0; i < onworklist.Count; i++)
                {
                    StrHtml.Append("<th>" + onworklist[i] + "</th>");
                }
                StrHtml.Append("</tr>");

                #endregion

                //总人数◇
                //在岗人数⊙
                //歇岗人数○
                foreach (Catering_Model.TempFWDanWeiModel modeldanwei in modelgangwei.DanWeiList.Values)
                {
                    #region 一个单位

                    int maxdw = 0;//单位最大行数
                    int personondw = 0;//单位在岗人数
                    if (modeldanwei != null && modeldanwei.PersonList != null && modeldanwei.PersonList.Count > 0)
                    {
                        foreach (Catering_Model.TempPersonList modelperlist in modeldanwei.PersonList.Values)//一个岗位
                        {
                            //岗位的最大行数
                            int tempmax = modelperlist.OnPersonNum > modelperlist.OutPersonNum ? modelperlist.OnPersonNum : modelperlist.OutPersonNum;
                            maxdw = tempmax > maxdw ? tempmax : maxdw;
                        }
                    }

                    StringBuilder workStr = new StringBuilder("");
                    for (int j = 0; j < maxdw; j++)
                    {
                        workStr.Append("<tr>");
                        if (j == 0)
                        {
                            workStr.Append("<td rowspan='" + maxdw + "'>" + modeldanwei.SName + "</td>");
                            workStr.Append("<td rowspan='" + maxdw + "'>◇</td>");
                        }
                        for (int i = 0; i < onworklist.Count; i++)
                        {
                            if (modeldanwei.PersonList.ContainsKey(onworklist[i]) && modeldanwei.PersonList[onworklist[i]].OnPersonNum > j)
                            {
                                workStr.Append("<td><a href=\"javascript:ShowUserInfo('" + modeldanwei.PersonList[onworklist[i]].OnPerson[j].PID + "')\">" + modeldanwei.PersonList[onworklist[i]].OnPerson[j].Name + "</a></td>");
                                personondw++;
                            }
                            else
                            {
                                workStr.Append("<td>&nbsp;</td>");
                            }
                        }
                        workStr.Append("</tr>");
                    }

                    #endregion

                    workStr.Replace("◇", (personondw).ToString());
                    StrHtml.Append(workStr.ToString());
                }
                StrHtml.Append("</table>");
                this.div_workinglist.InnerHtml = StrHtml.ToString();
            }

            #endregion


            #endregion
        }

        private void InitData(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                #region 数据提取

                //List<string> onworklist = new List<string>();//总岗位数
                //Catering_Model.TempGangWeiModel modelgangwei = new Catering_Model.TempGangWeiModel();

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string tpersonName = dt.Rows[i]["Name"].ToString();    //用户名
                    string tpName = dt.Rows[i]["PName"].ToString();          //岗位名称
                    string tsName = dt.Rows[i]["SName"].ToString();         //服务单位
                    int tpid = Convert.ToInt32(dt.Rows[i]["Pid"]);          //用户ID

                    //更改岗位数
                    if (!onworklist.Contains(tpName)) onworklist.Add(tpName);

                    //人员信息
                    Catering_Model.TempPerson modelperson = new Catering_Model.TempPerson();
                    modelperson.Name = tpersonName;
                    modelperson.PID = tpid;

                    if (modelgangwei.DanWeiList.ContainsKey(tsName))
                    {
                        if (modelgangwei.DanWeiList[tsName].PersonList.ContainsKey(tpName))//存在此岗位
                        {
                            modelgangwei.DanWeiList[tsName].PersonList[tpName].OnPerson.Add(modelgangwei.DanWeiList[tsName].PersonList[tpName].OnPersonNum, modelperson);
                            modelgangwei.DanWeiList[tsName].PersonList[tpName].OnPersonNum++;
                        }
                        else//不存在此岗位
                        {
                            Catering_Model.TempPersonList modelperlist = new Catering_Model.TempPersonList();
                            modelperlist.GangWei = tpName;
                            modelperlist.OnPerson.Add(modelperlist.OnPersonNum, modelperson);
                            modelperlist.OnPersonNum++;
                            modelgangwei.DanWeiList[tsName].PersonList.Add(modelperlist.GangWei, modelperlist);
                        }
                    }
                    else
                    {
                        Catering_Model.TempFWDanWeiModel modeldanwei = new Catering_Model.TempFWDanWeiModel();
                        Catering_Model.TempPersonList modelperlist = new Catering_Model.TempPersonList();
                        modelperlist.GangWei = tpName;
                        modelperlist.OnPerson.Add(modelperlist.OnPersonNum, modelperson);
                        modelperlist.OnPersonNum++;
                        modeldanwei.SName = tsName;
                        modeldanwei.PersonList.Add(modelperlist.GangWei, modelperlist);
                        modelgangwei.DanWeiList.Add(modeldanwei.SName, modeldanwei);
                    }
                }
                dt.Dispose();

                #endregion
            }
        }

        protected void Btn_Excel_Click(object sender, EventArgs e)
        {
            View_Monitor vm = new View_Monitor();
            DataTable dt = vm.GetZiYingCompanyAttendanceRecord();
            InitData(dt);

            if (onworklist.Count <= 0) return;
            Microsoft.Office.Interop.Excel.Application excel1 = null;
            Microsoft.Office.Interop.Excel._Worksheet ws = null;
            Microsoft.Office.Interop.Excel.Range canbie = null;
            string stick = DateTime.Now.Ticks.ToString();

            try
            {
                excel1 = new Microsoft.Office.Interop.Excel.Application();
                excel1.Application.Workbooks.Add(true);//引用Excel工作簿
                //Microsoft.Office.Interop.Excel._Worksheet ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                ws = (Microsoft.Office.Interop.Excel._Worksheet)excel1.ActiveSheet;//获取当前活动工作薄
                //Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题
                excel1.Visible = false;

                #region  表头

                canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, onworklist.Count + 2]);
                canbie.MergeCells = true;//合并单元格
                canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;//居中
                canbie.Font.Bold = 2;
                ws.Cells[1, 1] = DateTime.Now.ToLongDateString() + "自营公司岗位动态";

                #endregion

                #region 第一行标题

                canbie = ws.get_Range(ws.Cells[2, 1], ws.Cells[3, 1]);
                canbie.MergeCells = true;//合并单元格
                canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;//居中
                canbie.Font.Bold = 2;
                ws.Cells[2, 1] = "服务单位";

                canbie = ws.get_Range(ws.Cells[2, 2], ws.Cells[3, 2]);
                canbie.MergeCells = true;//合并单元格
                canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;//居中
                canbie.Font.Bold = 2;
                ws.Cells[2, 2] = "总人数";

                canbie = ws.get_Range(ws.Cells[2, 3], ws.Cells[2, onworklist.Count + 2]);
                canbie.MergeCells = true;//合并单元格
                canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;//居中
                canbie.Font.Bold = 2;
                ws.Cells[2, 3] = "岗位";

                for (int i = 0; i < onworklist.Count; i++)
                {
                    ws.Cells[3, i + 3] = onworklist[i];
                }

                #endregion

                #region 主要内容

                int canbiehangshu = 4;//服务单位行数

                if (modelgangwei != null && modelgangwei.DanWeiList.Count > 0)
                {
                    foreach (Catering_Model.TempFWDanWeiModel modeldanwei in modelgangwei.DanWeiList.Values)
                    {
                        int maxdw = 0;//单位最大行数
                        int personondw = 0;//单位在岗人数
                        if (modeldanwei != null && modeldanwei.PersonList != null && modeldanwei.PersonList.Count > 0)
                        {
                            foreach (Catering_Model.TempPersonList modelperlist in modeldanwei.PersonList.Values)//一个岗位
                            {
                                //岗位的最大行数
                                int tempmax = modelperlist.OnPersonNum > modelperlist.OutPersonNum ? modelperlist.OnPersonNum : modelperlist.OutPersonNum;
                                maxdw = tempmax > maxdw ? tempmax : maxdw;
                            }
                        }

                        canbie = ws.get_Range(ws.Cells[canbiehangshu, 1], ws.Cells[canbiehangshu + maxdw - 1, 1]);
                        canbie.MergeCells = true;//合并单元格
                        canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;//居中
                        canbie.Font.Bold = 2;
                        ws.Cells[canbiehangshu, 1] = modeldanwei.SName;

                        for (int j = 0; j < maxdw; j++)
                        {
                            for (int i = 0; i < onworklist.Count; i++)
                            {
                                if (modeldanwei.PersonList.ContainsKey(onworklist[i]) && modeldanwei.PersonList[onworklist[i]].OnPersonNum > j)
                                {
                                    ws.Cells[canbiehangshu + j, i + 3] = modeldanwei.PersonList[onworklist[i]].OnPerson[j].Name;
                                    personondw++;
                                }
                            }
                        }

                        canbie = ws.get_Range(ws.Cells[canbiehangshu, 2], ws.Cells[canbiehangshu + maxdw - 1, 2]);
                        canbie.MergeCells = true;//合并单元格
                        canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;//居中
                        canbie.Font.Bold = 2;
                        ws.Cells[canbiehangshu, 2] = personondw;

                        canbiehangshu += maxdw;
                    }

                    ws.Cells.EntireColumn.AutoFit();
                    canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[canbiehangshu - 1, onworklist.Count + 2]);
                    canbie.Borders.LineStyle = 1;
                }

                #endregion

                if (!Directory.Exists(Server.MapPath("../../xls_template"))) Directory.CreateDirectory(Server.MapPath("../../xls_template"));
                ws.SaveAs(Server.MapPath("../../xls_template") + "\\" + stick + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlAddIn8);
            }
            finally
            {
                if (excel1 != null)
                {
                    if (ws != null)
                    {
                        if (canbie != null)
                        {
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(canbie);
                            canbie = null;

                        }
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
                        ws = null;
                    }
                    excel1.Application.Workbooks.Close();
                    excel1.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1);
                    Toolss.KillExcel(excel1);
                    excel1 = null;
                    GC.Collect();
                }
            }

            #region 发送

            try
            {
                string path = Server.MapPath("../../xls_template") + "\\" + stick + ".xls";
                System.IO.FileInfo file = new System.IO.FileInfo(path);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息，,弹出另存为窗口  
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                //让浏览器头显示下载信息  
                Response.AddHeader("Content-Length", file.Length.ToString());
                // 指定返回一个不能被客户端读取的流，下载  
                Response.ContentType = "application/ms-excel";
                //把文件流下载到客户端  
                Response.WriteFile(file.FullName);
                Toolss.DeleteFile(Server.MapPath("../../xls_template") + "\\" + stick + ".xls");
                // 停止页面的执行
                Response.End();
            }
            catch
            {
            }

            #endregion
        }
    }
}